﻿using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using easyccms.Nhibernate.Infrastructure;

namespace easyccms.Nhibernate
{
    /// <summary>
    /// Session provider responsible for creating instance of Unit Of Work.
    /// </summary>
    public static class SessionProvider
    {
        private static ISessionFactory _sessionFactory = null;
        private static string _overrideConnectionString = "database";

        /// <summary>
        /// Gets the sessionFactory to create ISession instances. Created once during lifetime of worker process.
        /// </summary>
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    string connectionString = _overrideConnectionString;


                    _sessionFactory= Fluently.Configure()


              .Database(MsSqlConfiguration
                        //nacte z web.config connection string pro databazi s nazvem Kctc_Dev
                            .MsSql2008.ConnectionString(
                                c => c.FromConnectionStringWithKey("database"))
                            .ShowSql()
                            .ProxyFactoryFactory(
                                "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
              )
                        //Nastaveni aby se sql zobrazovalo v trace.axd
              .ExposeConfiguration(x => x.SetInterceptor(new SqlStatementInterceptor()))
                        //gets assigned mappings for assebly (Nastaveni kde najit mapping pro databazi)
              .Mappings(
                  x =>
                  x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()).Conventions.AddFromAssemblyOf
                      <IdConvention>().AddFromAssemblyOf<FKConvention>()).BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        /// <summary>
        /// Creates an NHibernate session.
        /// </summary>
        /// <returns>A new Session object.</returns>
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        /// <summary>
        /// Gets or sets the connection string to use to override the default (which is based on the current application environment). Specify null to use default. Default is null.
        /// </summary>
        /// <value>
        /// The override connection string.
        /// </value>
        public static string OverrideConnectionString
        {
            get { return _overrideConnectionString; }
            set { _overrideConnectionString = value; }
        }
    }
}
